package com.zhupanlin.config;

import com.zhupanlin.pojo.Configuration;
import com.zhupanlin.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 描述信息：
 *
 * @author zhupanlin
 * @version 1.0
 * @date 2025/2/8 17:41
 */
public class XMLMapperBuilder {
    
    private Configuration configuration;
    
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析 mapper.xml 文件 每一个标签对应一个 mapperStatement 放入 configuration 中
     * @param is
     * @throws DocumentException
     */
    public void parse(InputStream is) throws DocumentException {

        Document document = new SAXReader().read(is);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        List<Element> selectList = rootElement.selectNodes("//select");
        for (Element element : selectList) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(element.attributeValue("id"));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setSql(element.getTextTrim());
            String key = namespace + "." + mappedStatement.getId();
            mappedStatementMap.put(key, mappedStatement);
        }

    }
    
}